package com.zyz.I_多线程.线程通信;

/**
 * @author: vick
 * @Date: 2025/3/24
 * @Description:
 * @version: 1.0
 */
//仓库
public class Storage {
    //产品数量
    private int productNum = 0;
    private static final int MAX_PRODUCT = 20;
    private static final int MIN_PRODUCT = 1;

    //添加产品
    public synchronized void addProduct() {
        if (productNum < MAX_PRODUCT) {
            productNum++;
            System.out.println(Thread.currentThread().getName() + "生产了一个产品，现库存：" + productNum);
            //唤醒消费者消费
            this.notifyAll();
        }else {
            try {
                System.out.println(Thread.currentThread().getName() + "仓库满了，等待消费");
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    //减少产品
    public synchronized void minProduct() {
        if (productNum >= MIN_PRODUCT) {
            productNum--;
            System.out.println(Thread.currentThread().getName() + "消费了一个产品，现库存：" + productNum);
            //唤醒生产者生产
            this.notifyAll();
        }else {
            try {
                System.out.println(Thread.currentThread().getName() + "仓库空了，等待生产");
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
